import azure.cognitiveservices.speech as speechsdk
from config import subscription_key, service_region
import tkinter as tk


def transcribe_audio(file_path, text_box):
    # 打印配置信息
    print("Subscription Key:", subscription_key)
    print("Service Region:", service_region)
    print("File Path:", file_path)

    # 创建语音配置
    speech_config = speechsdk.SpeechConfig(subscription=subscription_key, region=service_region)
    # 创建音频配置
    audio_config = speechsdk.audio.AudioConfig(filename=file_path)
    # 创建语音识别器
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

    def result_callback(event_type, event):
        if event_type == speechsdk.SessionEventType.SPEECH_END_DETECTED:
            print("Speech End Detected")
        elif event_type == speechsdk.SessionEventType.RECOGNIZING:
            text_box.insert(tk.END, event.result.text)
        elif event_type == speechsdk.SessionEventType.RECOGNIZED:
            text_box.insert(tk.END, event.result.text + '\n')

    # 开始语音识别
    speech_recognizer.session_started.connect(lambda evt: print("Session started"))
    speech_recognizer.recognized.connect(lambda evt: result_callback(evt.event_type, evt))
    speech_recognizer.recognizing.connect(lambda evt: result_callback(evt.event_type, evt))
    speech_recognizer.session_stopped.connect(lambda evt: print("Session stopped"))

    speech_recognizer.start_continuous_recognition()
